package cn.seapon.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Logger;
/**
 * 
 * @author linzhv
 */
public class Encryption {

	public static void main(String[] args) {
//		String md5 = md5("123456");
//		String sha1 = sha1("123456");
//		String sha = sha("123456");
//		Logger.getGlobal().warning(md5);
//		Logger.getGlobal().warning(sha1);
//		Logger.getGlobal().warning(sha);
	}

	/**
	 * 40位SHA1
	 * http://www.3464.com/Tools/SHA1/
	 * @param decript
	 * @return String
	 */
	public static String sha1(String decript) {
		try {
			return encrypt(decript,"SHA-1");
		} catch (NoSuchAlgorithmException e) {
			Logger.getLogger("Encryption").warning(e.getMessage());
		}
		return "";
	}

	public static String sha(String decript) {
		try {
			return encrypt(decript,"SHA");
		} catch (NoSuchAlgorithmException e) {
			Logger.getLogger("Encryption").warning(e.getMessage());
		}
		return "";
	}

	/**
	 * http://www.cmd5.com/
	 * 
	 * @param input
	 * @return String
	 */
	public static String md5(String input) {
		try {
			return encrypt(input,"MD5");
		} catch (NoSuchAlgorithmException e) {
			Logger.getLogger("Encryption").warning(e.getMessage());
		}
		return "";
	}
	
	private static String encrypt(String string,String algorithm) throws NoSuchAlgorithmException {
		MessageDigest mdInst = MessageDigest.getInstance(algorithm);
		// 使用指定的字节更新摘要
		mdInst.update(string.getBytes());
		// 获得密文
		byte[] md = mdInst.digest();
		// 把密文转换成十六进制的字符串形式
		StringBuffer hexString = new StringBuffer();
		// 字节数组转换为 十六进制 数
		for (int i = 0; i < md.length; i++) {
			String shaHex = Integer.toHexString(md[i] & 0xFF);
			if (shaHex.length() < 2) {
				hexString.append(0);
			}
			hexString.append(shaHex);
		}
		return hexString.toString();
	}

}
